<?php

namespace app\admin\controller;

use wechat\src\WeChat;
use app\common\model\MpReply;
use app\common\model\MpRule;
use think\Validate;
/**
 * 微信上传数据，
 */
class Wechatauto extends base
{

    protected $wechat;

    public function _initialize()
    {
        $this->wechat = (new WeChat);
        $this->wechat->valid();
        $this->assign('action_name',$this->request->action());
     }

    /**
     * 自动回复
     * @author 314835050@qq.com
     * @param string $type
     * @return \think\response\View
     */
    public function autoreply($type = 'text')
    {

        switch ($type) {
            case 'text':
                $this->getRepayList('text');
                break;
            case 'news':
                $this->getRepayList('news');
                break;
//            case 'addon':
//                $ruleModel = new MpRule();
//                $data = $ruleModel->alias('r')
//                    ->where(['r.type' => 'addon'])
//                    ->join('__ADDONS__ a', 'a.addon=r.addon')->field('r.keyword,r.id,r.mpid,r.addon,r.type,r.status,a.name,a.desc,a.logo')
//                    ->select();
//                $this->assign('data', $data);
//                $this->assign('type', $type);
//                break;
            case 'voice':
                $this->getRepayList('voice');
                break;
            case 'image':
                $this->getRepayList('image');
                break;
            case 'video':
                $this->getRepayList('video');
                break;
            case 'music':
                $this->getRepayList('music');
                break;
            default:

                return $this->fetch();
                break;

        }
        return $this->fetch();
    }

    public function getRepayList($type)
    {
        $rePly = db('mp_rule')->alias('r')
            ->where(['r.type' => $type])
            ->join('__MP_REPLY__ p', 'p.reply_id=r.reply_id')
            ->order('r.id DESC')
            ->paginate(10);

        $this->assign('data', $rePly);
        $this->assign('type', $type);
    }



    /**
     * 处理特殊消息
     *
     * @return \think\response\View
     */
    public function special()
    {
        if ($this->request->isPost()) {
            $td = input();

            foreach ($td as $key => $val) {
                switch ($key) {
                    case 'image':
                        $this->doSpecial('image', $td);
                        break;
                    case 'voice':
                        $this->doSpecial('voice', $td);
                        break;
                    case 'video':
                        $this->doSpecial('video', $td);
                        break;
                    case 'shortvideo':
                        $this->doSpecial('shortvideo', $td);
                        break;
                    case 'location':
                        $this->doSpecial('location', $td);
                        break;
                    case 'event_location':
                        $this->doSpecial('event_location', $td);
                        break;
                    case 'link':
                        $this->doSpecial('link', $td);
                        break;
                    case 'view':
                        $this->doSpecial('view', $td);
                        break;
                    case 'subscribe':
                        $this->doSpecial('subscribe', $td);
                        break;
                    case 'unsubscribe':
                        $this->doSpecial('unsubscribe', $td);
                        break;
                    case 'unidentified':
                        $this->doSpecial('unidentified', $td);
                        break;
                }
            }
            ajaxMsg('1', '保存成功');


        } else {
            $where = [
                '0' => 'image',
                '1' => 'voice',
                '2' => 'video',
                '3' => 'shortvideo',
                '4' => 'location',
                '5' => 'event_location',
                '6' => 'link',
                '7' => 'view',
                '8' => 'subscribe',
                '9' => 'unsubscribe',
                '10' => 'unidentified',
            ];
            foreach ($where as $key => $v) {
                $result = db('mp_rule')
                    ->where('event', 'eq', $v)
                    ->field('addon,keyword,event')->find();
                if (empty($result)) {
                    $arr = [
                        'event' => 'nocol',
                        'keyword' => '',
                        'addon' => '',
                    ];
                    $this->assign($v, $arr);
                } else {
                    $this->assign($v, $result);
                }

            }


//            $addons = db('addons')->order('id Asc')->select();
            $this->assign('addons', 'dasd');
            return $this->fetch();
        }
    }

    public function doSpecial($type, $data)
    {
        switch ($data[$type]) {
            case 'nocol':
                db('mp_rule')->where([ 'event' => $type])->delete();
                break;
            case 'keyword':
                $key = $type . '_keyword';
                if ($data[$key]) {
                    if (db('mp_rule')->where([ 'event' => $type])->find()) {
                        db('mp_rule')->where([ 'event' => $type])->update(['keyword' => $data[$key], 'addon' => null]);
                    } else {
                        db('mp_rule')->insert([ 'event' => $type, 'keyword' => $data[$key]]);
                    }
                } else {
                    ajaxMsg('0', '表单中存在关键词没有填写');
                }
                break;
            case 'addon':
                $key = $type . '_addons';
                if ($data[$key]) {
                    if (db('mp_rule')->where([ 'event' => $type])->find()) {
                        db('mp_rule')->where([ 'event' => $type])->update(['addon' => $data[$key], 'keyword' => null]);
                    } else {
                        db('mp_rule')->insert([ 'event' => $type, 'addon' => $data[$key]]);
                    }
                } else {
                    ajaxMsg('0', '表单中存在应用没有选择');
                }
                break;
        }


    }

    /**
     * 增加关键词
     *
     * @return \think\response\View
     */
    public function addKeyword()
    {
        if ($this->request->isPost()) {
            $input = input();
            if (!isset($input['status'])) {
                $input['status'] = '0';
            }
            $data['keyword'] = trim($input['keyword']);
            $data['status'] = $input['status'];

            $ruleModel = new MpRule();
            $replyMode = new MpReply();
            $validate = new Validate(
                [
                    'keyword' => 'require',
                ],
                [
                    'keyword.require' => '关键词不能为空',
                ]
            );
            $result = $validate->check($input);
            if ($result === false) {
                ajaxMsg(0, $validate->getError());
            }
            switch ($input['type']) {
                case 'text':
                    $data['content'] = $input['content'];
                    $data['type'] = 'text';
                    $validate = new Validate(
                        [
                            'content' => 'require'

                        ],
                        [
                            'content.require' => '回复内容不能为空',
                        ]
                    );

                    $result = $validate->check($data);
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $material = [
                        
                        'content' => $data['content']
                    ];
//                    $this->material($input['type'], $material);
                    if ($reply_id = db('mp_reply')->insertGetId(['content' => $input['content'], 'type' => 'text'])) {
                        $data['reply_id'] = $reply_id;
                        $rule = $ruleModel->allowField(true)->save($data);
                    }
                    if ($reply_id && $rule) {

                        ajaxReturn(['url' => url('autoreply', ['type' => 'text'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                case 'news':

                    $validate = new Validate(
                        [
                            'title' => 'require',
                            'picurl' => 'require',
                            'link' => 'require',
                        ],
                        [
                            'title.require' => '标题不能为空',
                            'picurl.require' => '请上传图文封面图',
                            'link.require' => '连接不能为空',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $data['title'] = $input['title'];
                    $data['url'] = $input['picurl'];
                    $data['content'] = $input['news_content'];
                    $data['link'] = $input['link'];
                    $data['type'] = 'news';
                    if ($res_1 = $replyMode->allowField(true)->save($data)) {
                        $data['reply_id'] = $replyMode->reply_id;
                        if (!$res_2 = $ruleModel->allowField(true)->save($data)) {
                            $replyMode::destroy(['reply_id' => $data['reply_id']]);
                        }
                    }
                    if ($res_1 && $res_2) {
                        ajaxReturn(['url' => url('autoreply', ['type' => 'news'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                case 'addon':
                    $validate = new Validate(
                        [
                            'addons' => 'require',
                        ],
                        [
                            'addons.require' => '应用不能为空',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $data['keyword'] = $input['keyword'];
                    $data['type'] = 'addon';
                    $data['addon'] = $input['addons'];

                    if ($ruleModel->allowField(true)->save($data)) {
                        ajaxReturn(['url' => url('autoreply', ['type' => 'addon'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                case 'voice':
                    $validate = new Validate(
                        [
                            'voice_title' => 'require',
                            'voice' => 'require',
                        ],
                        [
                            'voice_title.require' => '语音名称不能为空',
                            'voice.require' => '请上传语音',
                        ]
                    );

                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }


//                    $filePath = explode(request()->domain(), $input['voice']);
                    $filePath = ROOT_PATH  . 'public\uploads\addkey' . DS .$input['voice'];
                    if(!is_file($filePath))ajaxMsg('0', '失败!没有文件');

                    if ($input['voice_staus_type'] == '0') {
                        $media = $this->wechat->instance('Material')->upload('voice',$filePath, 1);
                    }
                    if ($input['voice_staus_type'] == '1') {
                        $media = $this->wechat->instance('Material')->upload('voice',$filePath,0);
                    }

//                    $materialModel = new \app\common\model\Material();
//                    $materialArray = $materialModel->getMaterialByFind(['media_id' => $filePath]);
//                    if(empty($materialArray)){
//                        if ($input['voice_staus_type'] == '0') {
//                            $media = $this->wechat->instance('Material')->upload('voice',$filePath, 1);
//                        }
//                        if ($input['voice_staus_type'] == '1') {
//                            $media = $this->wechat->instance('Material')->upload('voice',$filePath, 0);
//                        }
//                    }else {
//                        if ($materialArray['from_type'] == 0) {//临时
//                            if (empty($materialArray['url'])) ajaxMsg('0', '失败！资源地址为空');
//                            $filePath = explode(request()->domain(), $materialArray['url']);
//                            if ($input['voice_staus_type'] == '0') {
//                                $media = $this->wechat->instance('Material')->upload('voice',$filePath, 1);
//                            }
//                            if ($input['voice_staus_type'] == '1') {
//                                $media = $this->wechat->instance('Material')->upload('voice',$filePath,0);
//                            }
//
//                        } else {//永久
//                            $media['media_id'] = $materialArray['media_id'];
//                        }
//                    }
                    if (isset($media['errcode']) && !empty($media['errcode'])) {
                        ajaxMsg(0, '上传失败：错误码：' .  $media['errcode'] . ' 错误内容：' . $media['errmsg']);
                    }

//                    if (isset($filePath[1]) && !empty($filePath[1])) {//认为新上传
//                         $data['path'] = $filePath[1];
//                        if ($input['voice_staus_type'] == '0') {
//                            $media = $this->wechat->instance('Material')->upload($filePath[1], 'voice',1);
//                        }
//                        if ($input['voice_staus_type'] == '1') {
//                            $media = $this->wechat->instance('Material')->upload($filePath[1], 'voice',0);
//                        }
//
//                    } else {//认为选择了永久或者暂时音频
//                        if (isset($filePath[0])) {
//                            $materialModel = new \app\common\model\Material();
//                            $materialArray = $materialModel->getMaterialByFind(['media_id' => $filePath[0]]);
//                            if ($materialArray['from_type'] == 0) {//临时
//                                if (empty($materialArray['url'])) ajaxMsg('0', '失败！资源地址为空');
//                                $filePath = explode(request()->domain(), $materialArray['url']);
//                                if ($input['voice_staus_type'] == '0') {
//                                    $media = $this->wechat->instance('Material')->upload($filePath[1], 'voice',1);
//                                }
//                                if ($input['voice_staus_type'] == '1') {
//                                    $media = $this->wechat->instance('Material')->upload($filePath[1], 'voice',0);
//                                }
//
//                            } else {//永久
//                                $media['media_id'] = $materialArray['media_id'];
//                            }
//                        }
//                    }
                    $data['title'] = $input['voice_title'];
                    $data['url'] = $input['voice'];
                    $data['type'] = 'voice';
                    $data['status_type'] = $input['voice_staus_type'];
                    $data['media_id'] = $media['media_id'];
                    $material = [
                        'title' => $data['title'],
                        'url' => $data['url'],
                        'media_id' => $data['media_id']
                    ];
                    $this->material($input['type'], $material, $input['voice_staus_type']);
                    if ($res_1 = $replyMode->allowField(true)->save($data)) {
                        $data['reply_id'] = $replyMode->reply_id;
                        if (!$res_2 = $ruleModel->allowField(true)->save($data)) {
                            $replyMode::destroy(['reply_id' => $data['reply_id']]);
                        }
                    }
                    if ($res_1 && $res_2) {
                        ajaxReturn(['url' => url('autoreply', ['type' => 'voice'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                case 'image':
                    set_time_limit(0);
//                    $materialModel = new \app\common\model\Material();
                    $validate = new Validate(
                        [
                            'reply_image' => 'require',
                        ],
                        [
                            'reply_image.require' => '请上传图片',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }

                    $filePath = ROOT_PATH  . 'public\uploads\addkey' . DS .$input['reply_image'];
                    if(!is_file($filePath))ajaxMsg('0', '失败!没有文件');
                    if ($input['image_staus_type'] == '0') {
                        $media = $this->wechat->instance('Material')->upload('image',$filePath,1);
                    }
                    if ($input['image_staus_type'] == '1') {
                        $media = $this->wechat->instance('Material')->upload('image',$filePath,0);
                    }
                    if (isset($media['errcode']) && !empty($media['errcode'])) {
                        ajaxMsg(0, '上传失败：错误码：' .  $media['errcode'] . ' 错误内容：' . $media['errmsg']);
                    }

//                    $sting = getSetting($this->mid, 'cloud');
//                    if (isset($sting['qiniu']['status']) && $sting['qiniu']['status'] == 1) {
//                        $ext = strrchr($input['reply_image'], '.');
//                        $fileName_h = md5(rand_string(12)) . $ext;
//                        $filePath[1] = dowloadImage($input['reply_image'], './uploads/', $fileName_h);
//                        if (!$filePath[1]) {
//                            ajaxMsg(0, '获取图片失败');
//                        }
//                    } else {
//                        $ext = strrchr($input['reply_image'], '.');
//                        $fileName_h = md5(rand_string(12)) . $ext;
//                        $filePath[1] = dowloadImage($input['reply_image'], './uploads/', $fileName_h);
//                        // $filePath = explode(getHostDomain(),$input['reply_image']);//strpos
//                    }
//                    if (!strpos($input['reply_image'], 'show/image') || !strpos($input['reply_image'], 'qpic.cn')) {
//                        //认为本地资源或者新上传
//                        if (isset($filePath[1]) && !empty($filePath[1])) {
//                            $data['path'] = $filePath[1];
//                            if ($input['image_staus_type'] == '0') {
//                                $media = uploadMedia($filePath[1], 'image');
//                            }
//                            if ($input['image_staus_type'] == '1') {
//                                $media = uploadForeverMedia($filePath[1], 'image');
//                            }
//
//                        }
//                    } else {
//                        //认为永久、类型永久或者临时请忽略
//                        $materialArray = $materialModel->getMaterialByFind(['url' => $input['reply_image']]);
//                        $media['media_id'] = $materialArray['media_id'];
//
//                    }
                    $data['url'] = $input['reply_image'];
                    $data['type'] = 'image';
                    $data['media_id'] = $media['media_id'];
                    $data['status_type'] = $input['image_staus_type'];
                    $material = [
                        
                        'url' => $data['url'],
                        'media_id' => $data['media_id']
                    ];
//                    $this->material($input['type'], $material, $input['image_staus_type']);
                    if ($res_1 = $replyMode->allowField(true)->save($data)) {
                        $data['reply_id'] = $replyMode->reply_id;
                        if (!$res_2 = $ruleModel->allowField(true)->save($data)) {
                            $replyMode::destroy(['reply_id' => $data['reply_id']]);
                        }
                    }
                    if ($res_1 && $res_2) {
                        ajaxReturn(['url' => url('autoreply', ['type' => 'image'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                case 'video':
                    $validate = new Validate(
                        [
                            'video_title' => 'require',
                            'reply_video' => 'require',
                        ],
                        [
                            'video_title.require' => '视频标题不能为空',
                            'reply_video.require' => '请上传视频',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }

                    $filePath = ROOT_PATH  . 'public\uploads\addkey' . DS .$input['reply_video'];
                    if(!is_file($filePath))ajaxMsg('0', '失败!没有文件');
                    if ($input['video_staus_type'] == '0') {
                        $media = $this->wechat->instance('Material')->upload('video',$filePath,1);
                    }
                    if ($input['video_staus_type'] == '1') {
                        $media = $this->wechat->instance('Material')->upload('video',$filePath,0,$input);
                    }
//                    $materialModel = new \app\common\model\Material();
//                    $materialArray = $materialModel->getMaterialByFind(['media_id' => $filePath]);
//                    if(empty($materialArray)){
//                        if ($input['video_staus_type'] == '0') {
//                            $media = $this->wechat->instance('Material')->upload('video',$filePath,1);
//                        }
//                        if ($input['video_staus_type'] == '1') {
//                            $media = $this->wechat->instance('Material')->upload('video',$filePath,0);
//                        }
//                    }else {
//
//                        if ($materialArray['from_type'] == 0) {//临时
//                            if (empty($materialArray['url'])) ajaxMsg('0', '失败！资源地址为空');
//                            $filePath = explode(request()->domain(), $materialArray['url']);
//                            if ($input['video_staus_type'] == '0') {
//                                $media = $this->wechat->instance('Material')->upload('video',$filePath,1);
//                            }
//                            if ($input['video_staus_type'] == '1') {
//                                $media = $this->wechat->instance('Material')->upload('video',$filePath,0);
//                            }
//
//                        } else {//永久
//                            $media['media_id'] = $materialArray['media_id'];
//                        }
//                    }
                    if (isset($media['errcode']) && !empty($media['errcode'])) {
                        ajaxMsg(0, '上传失败：错误码：' .  $media['errcode'] . ' 错误内容：' . $media['errmsg']);
                    }
//                    $filePath = explode(getHostDomain(), $input['reply_video']);
//                    if (isset($filePath[1]) && !empty($filePath[1])) {
//                        if ($input['video_staus_type'] == '0') {
//                            $media = uploadMedia($filePath[1], 'video');
//                        }
//                        if ($input['video_staus_type'] == '1') {
//
//                            $media = uploadForeverMedia($filePath[1], 'video', true, ['title' => $input['video_title'], 'introduction' => $input['video_content']]);
//
//                        }
//
//                    } else {//认为选择了永久或者暂时音频
//                        if (isset($filePath[0])) {
//                            $materialModel = new \app\common\model\Material();
//                            $materialArray = $materialModel->getMaterialByFind(['media_id' => $filePath[0]]);
//                            if ($materialArray['from_type'] == 0) {//临时
//                                if (empty($materialArray['url'])) ajaxMsg('0', '失败！资源地址为空');
//                                $filePath = explode(getHostDomain(), $materialArray['url']);
//                                if ($input['video_staus_type'] == '0') {
//                                    $media = uploadMedia($filePath[1], 'video');
//                                }
//                                if ($input['video_staus_type'] == '1') {
//
//                                    $media = uploadForeverMedia($filePath[1], 'video', true, ['title' => $input['video_title'], 'introduction' => $input['video_content']]);
//
//                                }
//
//                            } else {//永久
//                                $media['media_id'] = $materialArray['media_id'];
//                            }
//                        }
//                    }
                    $data['title'] = $input['video_title'];
                    $data['content'] = $input['video_content'];
                    $data['url'] = $input['reply_video'];
                    $data['type'] = 'video';
                    $data['status_type'] = $input['video_staus_type'];
                    $data['media_id'] = $media['media_id'];
                    $material = [
                        
                        'title' => $data['title'],
                        'content' => $data['content'],
                        'url' => $data['url'],
                        'media_id' => $data['media_id']
                    ];
                    $this->material($input['type'], $material, $input['video_staus_type']);
                    if ($res_1 = $replyMode->allowField(true)->save($data)) {
                        $data['reply_id'] = $replyMode->reply_id;
                        if (!$res_2 = $ruleModel->allowField(true)->save($data)) {
                            $replyMode::destroy(['reply_id' => $data['reply_id']]);
                        }
                    }
                    if ($res_1 && $res_2) {
                        ajaxReturn(['url' => url('autoreply', ['type' => 'video'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                case 'music':
                    $validate = new Validate(
                        [
                            'music_title' => 'require',
                            'music' => 'require',
                        ],
                        [
                            'music_title.require' => '音乐标题不能为空',
                            'music.require' => '请上传音乐',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $data['title'] = $input['music_title'];
                    $data['url'] = $input['music'];
                    $data['link'] = $input['music_link'];
                    $data['type'] = 'music';
                    $data['content'] = $input['music_content'];
                    $material = [

                        'title' => $data['title'],
                        'content' => $data['content'],
                        'url' => $data['url'],
                    ];
                    $this->material($input['type'], $material);
                    if ($res_1 = $replyMode->allowField(true)->save($data)) {
                        $data['reply_id'] = $replyMode->reply_id;
                        if (!$res_2 = $ruleModel->allowField(true)->save($data)) {
                            $replyMode::destroy(['reply_id' => $data['reply_id']]);
                        }
                    }
                    if ($res_1 && $res_2) {
                        ajaxReturn(['url' => url('autoreply', ['type' => 'music'])], 1, '提交成功');
                    } else {
                        ajaxMsg(0, '提交失败');
                    }
                    break;
                default:

                    return $this->fetch();
                    break;

            }
        } else {
//            $addons = db('addons')->order('id Asc')->select();
            $this->assign('addons', 'eew');
            return $this->fetch('addkeyword');
        }

    }


    public function editautoreply()
    {
        $id = input('get.id');
        $post = input('post.');
        $rePly = db('mp_rule')->alias('r')
            ->where([ 'r.id' => $id])
            ->join('__MP_REPLY__ p', 'p.reply_id=r.reply_id', 'left')
            ->field('r.*,p.reply_id,p.title,p.content,p.url,p.link,p.status_type,p.media_id')
            ->find();
        if (empty($rePly)) {
            echo '内容不存在';
            exit;
        }

        if ($this->request->isAjax()) {
            $validate = new Validate(
                [
                    'keyword' => 'require',
                ],
                [
                    'keyword.require' => '关键词不能为空',
                ]
            );
            $result = $validate->check($post);
            if ($result === false) {
                ajaxMsg(0, $validate->getError());
            }
            $status = isset($post['status']) ? 1 : 0;
//            $data['status'] = $status;
            MpRule::update(['keyword' => trim($post['keyword']), 'status' => $status], [ 'id' => $id]);

            switch ($rePly['type']) {
                case 'text':
                    MpReply::update(['content' => $post['content']], ['reply_id' => $rePly['reply_id']]);
                    ajaxMsg(1, '修改成功');
                    break;
                case 'news':
                    $validate = new Validate(
                        [
                            'title' => 'require',
                            'picurl' => 'require',
                            'link' => 'require',
                        ],
                        [
                            'title.require' => '标题不能为空',
                            'picurl.require' => '请上传图文封面图',
                            'link.require' => '连接不能为空',
                        ]
                    );
                    $result = $validate->check($post);
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $data['title'] = $post['title'];
                    $data['url'] = $post['picurl'];
                    $data['content'] = $post['news_content'];
                    $data['link'] = $post['link'];
                    MpReply::update($data, ['reply_id' => $rePly['reply_id']]);
                    ajaxMsg(1, '修改成功');
                    break;
                case 'addon':
                    $validate = new Validate(
                        [
                            'addons' => 'require',
                        ],
                        [
                            'addons.require' => '应用不能为空',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $data['addon'] = $post['addons'];
                    MpRule::update(['addon' => $post['addons']], [ 'id' => $id]);
                    ajaxMsg(1, '修改成功');
                    break;
                case 'voice':
                    $validate = new Validate(
                        [
                            'voice_title' => 'require',
                            'voice' => 'require',
                        ],
                        [
                            'voice_title.require' => '语音名称不能为空',
                            'voice.require' => '请上传语音',
                        ]
                    );

                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    if ($rePly['url'] != $post['voice'] || $rePly['status_type'] != $post['voice_staus_type']) {

                        $filePath = ROOT_PATH  . 'public\uploads\addkey' . DS .$post['voice'];
                        if(!is_file($filePath))ajaxMsg('0', '失败!没有文件');

                        if ($post['voice_staus_type'] == '0') {
                            $media = $this->wechat->instance('Material')->upload('voice',$filePath, 1);
                        }
                        if ($post['voice_staus_type'] == '1') {
                            $media = $this->wechat->instance('Material')->upload('voice',$filePath,0);
                        }
//                        $filePath = explode(getHostDomain(), $post['voice']);
//                        if (isset($filePath[1]) && !empty($filePath[1])) {//认为新上传
//                            $data['path'] = $filePath[1];
//                            if ($post['voice_staus_type'] == '0') {
//                                $media = uploadMedia($filePath[1], 'voice');
//                            }
//                            if ($post['voice_staus_type'] == '1') {
//
//                                $media = uploadForeverMedia($filePath[1], 'voice');
//
//                            }
//
//                        } else {//认为选择了永久或者暂时音频
//                            if (isset($filePath[0])) {
//                                $materialModel = new \app\common\model\Material();
//                                $materialArray = $materialModel->getMaterialByFind(['media_id' => $filePath[0]]);
//                                if ($materialArray['from_type'] == 0) {//临时
//                                    if (empty($materialArray['url'])) ajaxMsg('0', '失败！资源地址为空');
//                                    $filePath = explode(getHostDomain(), $materialArray['url']);
//                                    if ($post['voice_staus_type'] == '0') {
//                                        $media = uploadMedia($filePath[1], 'voice');
//                                    }
//                                    if ($post['voice_staus_type'] == '1') {
//
//                                        $media = uploadForeverMedia($filePath[1], 'voice');
//
//                                    }
//
//                                } else {//永久
//                                    $media['media_id'] = $materialArray['media_id'];
//                                }
//                            }
//                        }
                        $data['media_id'] = $media['media_id'];
                        $material = [
                            
                            'title' => $post['voice_title'],
                            'url' => $post['voice'],
                            'media_id' => $data['media_id']
                        ];
                        $this->material('voice', $material, $post['voice_staus_type']);
                    }
                    $data['title'] = $post['voice_title'];
                    $data['url'] = $post['voice'];
                    $data['type'] = 'voice';
                    $data['status_type'] = $post['voice_staus_type'];
                    MpReply::update($data, ['reply_id' => $rePly['reply_id']]);
                    ajaxMsg(1, '修改成功');
                    break;
                case 'image':
                    $input = $post;
//                    $materialModel = new \app\common\model\Material();
                    $validate = new Validate(
                        [
                            'reply_image' => 'require',
                        ],
                        [
                            'reply_image.require' => '请上传图片',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    if ($rePly['url'] != $input['reply_image']||$rePly['status_type'] != $post['image_staus_type']) {
                        $filePath = ROOT_PATH  . 'public\uploads\addkey' . DS .$input['reply_image'];
                        if(!is_file($filePath))ajaxMsg('0', '失败!没有文件');

                        if ($input['image_staus_type'] == '0') {
                            $media = $this->wechat->instance('Material')->upload('image',$filePath,1);
                        }
                        if ($input['image_staus_type'] == '1') {
                            $media = $this->wechat->instance('Material')->upload('image',$filePath,0);
                        }
                        if (isset($media['errcode']) && !empty($media['errcode'])) {
                            ajaxMsg(0, '上传失败：错误码：' .  $media['errcode'] . ' 错误内容：' . $media['errmsg']);
                        }

//                        $sting = getSetting($this->mid, 'cloud');
//                        if (isset($sting['qiniu']['status']) && $sting['qiniu']['status'] == 1) {
//                            $ext = strrchr($input['reply_image'], '.');
//                            $fileName_h = md5(rand_string(12)) . $ext;
//                            $filePath[1] = dowloadImage($input['reply_image'], './uploads/', $fileName_h);
//                            if (!$filePath[1]) {
//                                ajaxMsg(0, '获取图片失败');
//                            }
//                        } else {
//                            $ext = strrchr($input['reply_image'], '.');
//                            $fileName_h = md5(rand_string(12)) . $ext;
//                            $filePath[1] = dowloadImage($input['reply_image'], './uploads/', $fileName_h);
//                            // $filePath = explode(getHostDomain(),$input['reply_image']);//strpos
//                        }
//                        if (!strpos($input['reply_image'], 'show/image') || !strpos($input['reply_image'], 'qpic.cn')) {
//                            //认为本地资源或者新上传
//                            if (isset($filePath[1]) && !empty($filePath[1])) {
//                                $data['path'] = $filePath[1];
//                                if ($input['image_staus_type'] == '0') {
//                                    $media = uploadMedia($filePath[1], 'image');
//                                }
//                                if ($input['image_staus_type'] == '1') {
//                                    $media = uploadForeverMedia($filePath[1], 'image');
//                                }
//
//                            }
//                        } else {
//                            //认为永久、类型永久或者临时请忽略
//                            $materialArray = $materialModel->getMaterialByFind(['url' => $input['reply_image']]);
//                            $media['media_id'] = $materialArray['media_id'];
//
//                        }
                        $data['url'] = $input['reply_image'];
                        $data['type'] = 'image';
                        $data['media_id'] = $media['media_id'];
                        $data['status_type'] = $input['image_staus_type'];
                        $material = [
                            
                            'url' => $data['url'],
                            'media_id' => $data['media_id']
                        ];
                        $this->material('image', $material, $input['image_staus_type']);
                        MpReply::update($data, ['reply_id' => $rePly['reply_id']]);
                    }
                    ajaxMsg(1, '修改成功');
                    break;
                case 'video':
                    $input = $post;
                    $validate = new Validate(
                        [
                            'video_title' => 'require',
                            'reply_video' => 'require',
                        ],
                        [
                            'video_title.require' => '视频标题不能为空',
                            'reply_video.require' => '请上传视频',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    if ($rePly['url'] != $input['reply_video']||$rePly['status_type'] != $post['video_staus_type']) {

                        $filePath = ROOT_PATH  . 'public\uploads\addkey' . DS .$input['reply_video'];
                        if(!is_file($filePath))ajaxMsg('0', '失败!没有文件');

                        if ($input['video_staus_type'] == '0') {
                            $media = $this->wechat->instance('Material')->upload('video',$filePath,1);
                        }
                        if ($input['video_staus_type'] == '1') {
                            $media = $this->wechat->instance('Material')->upload('video',$filePath,0,$input);
                        }

                        if (isset($media['errcode']) && !empty($media['errcode'])) {
                            ajaxMsg(0, '上传失败：错误码：' .  $media['errcode'] . ' 错误内容：' . $media['errmsg']);
                        }


//                        $filePath = explode(getHostDomain(), $input['reply_video']);
//                        if (isset($filePath[1]) && !empty($filePath[1])) {
//                            if ($input['video_staus_type'] == '0') {
//                                $media = uploadMedia($filePath[1], 'video');
//                            }
//                            if ($input['video_staus_type'] == '1') {
//
//                                $media = uploadForeverMedia($filePath[1], 'video', true, ['title' => $input['video_title'], 'introduction' => $input['video_content']]);
//
//                            }
//
//                        } else {//认为选择了永久或者暂时音频
//                            if (isset($filePath[0])) {
//                                $materialModel = new \app\common\model\Material();
//                                $materialArray = $materialModel->getMaterialByFind(['media_id' => $filePath[0]]);
//                                if ($materialArray['from_type'] == 0) {//临时
//                                    if (empty($materialArray['url'])) ajaxMsg('0', '失败！资源地址为空');
//                                    $filePath = explode(getHostDomain(), $materialArray['url']);
//                                    if ($input['video_staus_type'] == '0') {
//                                        $media = uploadMedia($filePath[1], 'video');
//                                    }
//                                    if ($input['video_staus_type'] == '1') {
//
//                                        $media = uploadForeverMedia($filePath[1], 'video', true, ['title' => $input['video_title'], 'introduction' => $input['video_content']]);
//
//                                    }
//
//                                } else {//永久
//                                    $media['media_id'] = $materialArray['media_id'];
//                                }
//                            }
//                        }

                        $data['url'] = $input['reply_video'];
                        $data['status_type'] = $input['video_staus_type'];
                        $data['media_id'] = $media['media_id'];
                        $material = [
                            'title' => $input['video_title'],
                            'content' => $input['video_content'],
                            'url' => $data['url'],
                            'media_id' => $data['media_id']
                        ];
                        $this->material('video', $material, $input['video_staus_type']);
                    }
                    $data['title'] = $input['video_title'];
                    $data['content'] = $input['video_content'];
                    MpReply::update($data, ['reply_id' => $rePly['reply_id']]);
                    ajaxMsg(1, '修改成功');
                    break;
                case 'music':
                    $input = $post;
                    $validate = new Validate(
                        [
                            'music_title' => 'require',
                            'music' => 'require',
                        ],
                        [
                            'music_title.require' => '音乐标题不能为空',
                            'music.require' => '请上传音乐',
                        ]
                    );
                    $result = $validate->check(input());
                    if ($result === false) {
                        ajaxMsg(0, $validate->getError());
                    }
                    $data['title'] = $input['music_title'];
                    $data['url'] = $input['music'];
                    $data['link'] = $input['music_link'];
                    $data['type'] = 'music';
                    $data['content'] = $input['music_content'];
                    $material = [
                        'title' => $data['title'],
                        'content' => $data['content'],
                        'url' => $data['url'],
                    ];
                    $this->material('music', $material);
                    MpReply::update($data, ['reply_id' => $rePly['reply_id']]);
                    ajaxMsg(1, '修改成功');
                    break;
            }

        } else {
            if ($rePly['type'] == 'addon') {
//                $addons = db('addons')->order('id Asc')->select();
                $this->assign('addons','22');
            }
            $this->assign('data', $rePly);
            $this->assign('type', $rePly['type']);
            return view();
        }
    }


    public function updateRule($id = '', $status = '')
    {
        $model = new MpRule();
        $model->save(['status' => $status], ['id' => $id]);
        ajaxMsg(1, '改变状态成功');
    }

    public function delRule($id = '')
    {
        $where = [
            'id' => $id
        ];
        $model = new MpRule();
        if ($model->delRule($where)) {
            ajaxMsg(1, '成功删除');
        } else {
            ajaxMsg(0, '删除失败');
        }
    }


    public function material($type = '', $data = [], $materialStatus = 0)
    {
        $model = new \app\common\model\Material();
        $model->addMaterial($type, $data, $materialStatus);
    }


    /**
     * 发送消息
     */
    public function save()
    {

        $val ='C:\xampp\htdocs\tp5only\public\uploads\addkey\5ac4dc1798396.mp4';

        $input=[
            'video_title' => 'hghgf111',
            'video_content' => 'v发的时刻'
        ];
        $result = $this->wechat->instance('Material')->upload('video',$val,0,$input);
if(isset($result['media_id'])){

		$data = ['media_id' => $result['media_id'], 'filename' => '5a9d59569e1d0.jpg','rtype'=>'image','created_at'=>time()];
}
        print_r($result);

//		print_r($data);
exit();
		//db('media')->insert($data);
    }
}
